<?php
namespace Home\Controller;

use Think\Controller;

class IndexController extends CommonController
{
  public function index()
  {
    return_data("success", "wdds.api.ok");
  }

  public function slides()
  {
    $app_id = I('app_id');

    $adverts = M('adverts')->where("app_id = $app_id and types in (1,2) and status = 1")->order("orderby asc")->select();

    foreach ($adverts as $key => $value) {
      $slides[] = array('url'=> $value['image'], 'page'=> $value['link'],'appid'=> $value['appid'],'is_applet'=> $value['is_applet']);
    }

    return_data("success", "slides.success", $slides);
  }

  //小店优选
  public function hots()
  {
        $app_id = I('app_id');

        $products = M('adverts')->where("app_id = $app_id and types = 3 and status = 1")->order("orderby asc")->select();

        foreach ($products as $key => $value) {
            $hots[] = array('title'=> $value['title'], 'desc'=> $value['desc'], 'image'=> $value['image'], 'page'=> $value['link'],'appid'=> $value['appid'],'is_applet'=> $value['is_applet']);
        }

        return_data("success", "push.products.success", $hots);
  }

  public function app_info()
  {
    $app_id = I('app_id');
    $app = M('apps')->field('id, name,is_search, kfphone, kfwechat, descrip, share_img, alipay_max_amount, link, shop_login_logo, withdraw_min_amount, withdraw_max_amount, withdraw_daily_times, alipay_switch, company_name')->where("id = $app_id")->find();

    if ($app) {
      return_data("success", "app.info.success", $app);
    } else {
      return_data('error', 'app.info.error');
    }
  }

  /**
   * [普通用户 一般微信公众号授权登录-token]
   * @return [type] [description]
   */
  public function login_wx_user()
  {
    $code = I('code');

    if ($code) {
      //获取code码，以获取openid
      $openid = D("Wechat")->get_openid($code);
      if (!$openid) {
        return_data("error", "login_wx_user.openid.empty");
      } else {
        return_data("success", "login_wx_user.openid.success", $openid);
      }
    } else {
      return_data("error", "login_wx_user.code.empty");
    }
  }

  /**
   * 小程序更新用户信息
   * @return [type] [description]
   */
  public function xcx_user_update()
  {
    Vendor("Wxapplet.wxBizDataCrypt");

    $payload = file_get_contents('php://input');
    $json = json_decode($payload);

    $session_3rd = $json->session_3rd;
    $session_3rd = S($session_3rd);
    $openid = $session_3rd['openid'];

    $user = M('users')->where("xcx_openid='$openid'")->find();
    if ($user) {
      $rawData = $json->rawData;
      $signature = $json->signature;
      $encryptedData = $json->encryptedData;
      $iv = $json->iv;

      $sign = sha1($rawData . $user['session_key']);
      if ($sign !== $signature) {
        return_data("error", "wx_min_login.signature.error", $sign);
      }

      $app_info = M('apps')->where("id = {$user['app_id']}")->find();
      $pc = new \WXBizDataCrypt($app_info['cappid_applet'], $user['session_key']);
      $errCode = $pc->decryptData($encryptedData, $iv, $data);

      if ($errCode == 0) {
        $data = json_decode($data);

        $user['nickname'] = $data->nickName;
        $user['avatar'] = $data->avatarUrl;
        $user['updated_at'] = gmtime();
        $user['union_id'] = $data->unionId;
        $user_id = M('users')->where("xcx_openid='$openid'")->save($user);

        if ($user_id) {
          // $token = D("users")->create_token($session_3rd['user_id']);
          return_data("success", "user.update.success", $token);
        } else {
          return_data("error", "user.update.error");
        }
      } else {
        return_data("error", "xcx_user_update.encryptData.error", $errCode);
      }
    } else {
      return_data("error", "xcx_user_update.user.not.exists");
    }
  }

  /**
   * 小程序用户登录换取3rd_session
   * 存储session_key / openid
   * @return [type] [description]
   */
  public function wx_xcx_login()
  {
    $code = I('code');
    $app_id = I('app_id');
    if ($code) {
      $res = D("Wechat")->get_openid_applet($code, $app_id);
      if(!$res['openid']){
        return_data("error", "user.openid.empty", $res);
      }
      //通过openid找用户，更新对应session_key
      $user = M("users")->where("xcx_openid='$res[openid]'")->find();
      if ($user) {
        $data['session_key'] = $res['session_key'];
        if (!$user['app_id']) {
          $data['app_id'] = $app_id;
        }
        M("users")->where("xcx_openid='$res[openid]'")->save($data);

        $user_id = $user['id'];
      } else {
        $data = array(
          'xcx_openid' =>  $res['openid'],
          'session_key' => $res['session_key'],
          'created_at' => $this->current_time,
          'updated_at'=> $this->current_time,
          'nickname' => I('nickname')?I('nickname'):'匿名',
          'app_id' => $app_id,
          'avatar' => I('avatar')?I('avatar'):'http://wdds-app.b0.upaiyun.com/default/avatar.png');

        $user = M('users');
        $user_id = $user->data($data)->add($data);
      }

      //设置3rd_session
      $session_3rd = md5($user_id.randomFromDev(16));
      $res['user_id'] = $user_id;
      S($session_3rd, $res, gmtime() + $res['expires_in']);

      $token = D("users")->create_token($user_id);

      return_data("success", "user.token.success", array('session_3rd' => $session_3rd, 'token'=> $token));
    } else {
      return_data("error", "user.token.error", $res);
    }
  }

  /**
   * [商户登录]
   * @return [type] [description]
   */
  public function business_login()
  {
    // {'phone':,'code', 'token':}
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    extract($data);

    //验证合法性
    if (!$phone) {
      return_data("error", "users.phone.blank");
    }

    //检查商户店铺
    $where = array('phone' => $phone, 'app_id' => $data['app_id']);
    $shop = M("shops")->field('*')->where($where)->find();
    if (!$shop) {
      return_data("error", "shops.not.exists");
    }
    if ($shop['status'] != 1) {
      return_data("error", "shops.status.deny");
    }

    $user = $this->check_login();
    if (!$user) {
      return_data("error", "business.token.error");
    }

    //如果商户用户存在
    if ($user && $user['types'] == 1 && $user['shop_id'] == $shop['id']) {
      return_data("success", "business.login.success", $shop);
    }

    $business = M('users')->field('nickname')->where("shop_id=$shop[id]")->find();
    //商户首次绑定
    if ($user && !$business) {
      $data =  array('types' => 1,
        'phone' => $phone,
        'shop_id' => $shop['id'],
        'updated_at' => $this->current_time);
      M('users')->where("id=$user[user_id]")->save($data);

      return_data("success", "business.login.success", $shop);
    } else {
      return_data("error", "business.has.bind", $business);
    }
  }

  public function shop_login()
  {
    Vendor("Wxapplet.wxBizDataCrypt");
    $user = $this->check_login();
    if (!$user) {
      return_data("error", "business.token.error");
    }

    $payload = file_get_contents('php://input');
    $json = json_decode($payload, true);

    $session_3rd = S($json['session_3rd']);
    $user = M('users')->where("xcx_openid='{$session_3rd[openid]}'")->find();

    $app_info = $this->app_info;

    $pc = new \WXBizDataCrypt($app_info['cappid_applet'], $user['session_key']);
    $err_code = $pc->decryptData($json['encrypted_data'], $json['iv'], $data);

    if ($err_code != 0) {
      return_data('error', 'shop.phone.auth.fail');
    }

    $data = json_decode($data, true);

    //检查商户店铺
    $where = array('phone' => $data['phoneNumber'], 'app_id' => $user['app_id']);
    $shop = M("shops")->field('*')->where($where)->find();

    if (!$shop) {
      return_data("error", "shops.not.exists");
    }
    if ($shop['status'] != 1) {
      return_data("error", "shops.status.deny");
    }

    //如果商户用户存在
    if ($user && $user['types'] == 1 && $user['shop_id'] == $shop['id']) {
      return_data("success", "business.login.success", $shop);
    }

    $business = M('users')->field('nickname')->where("shop_id=$shop[id]")->find();
    //商户首次绑定
    if ($user && !$business) {
      $data =  array('types' => 1,
        'phone' => $phone,
        'shop_id' => $shop['id'],
        'updated_at' => $this->current_time);
      M('users')->where("id=$user[user_id]")->save($data);

      return_data("success", "business.login.success", $shop);
    } else {
      return_data("error", "business.has.bind", $business);
    }
  }

  public function helps()
  {
    $this->check_login();
    $types = I('types', 1);
    $where = "app_id={$this->app_id} and status = 1 and types = $types";
    $order = "orderby desc";

    $list = M('helps')->where($where)->order($order)->select();

    foreach ($list as $key => &$info) {
      $info['updated_at'] = date("Y-m-d", $info['updated_at']);//local_time($info['created_at']);
    }

    if ($list) {
      return_data("success", "index.history.success", $list);
    } else {
      return_data("error", "index.history.empty");
    }
  }

  /**
   * [首页模式]
   * @return [type] [description]
   */
  public function index_type()
  {
      $app_id = I('app_id');
      $app = M('apps')->field('id, index_types, hot_title')->where("id = $app_id")->find();

      if ($app) {
          return_data("success", "index.type.app.success", $app);
      } else {
          return_data('success', 'index.type.app.error',"{'hot_title':'','index_type':'1'}");
      }

  }
}
